﻿using System;
using System.Collections.Specialized;


namespace LiveMail
{
    /// <summary>
    /// retrieve mail via pop.
    /// </summary>
    public class PopMail : TestMailBase
    {

        /// <summary>
        /// ctor method.
        /// </summary>
        public PopMail(string host, int port, bool useSsl)
            : base(host, port, useSsl)
        {
        }

        /// <summary>
        /// connect to server.
        /// </summary>
        public override void Connect()
        {
            base.Connect();
            ReadServerResponseText();
        }

        /// <summary>
        /// user login.
        /// </summary>
        public override void AuthenticateUser(string user, string pass)
        {
            SendCommand("USER " + user);
            string text = SendCommand("PASS " + pass);

            if (!IsValidResponse(text))
            {
                throw new InvalidOperationException("login failed." + text);
            }
        }

        /// <summary>
        /// get total mail count.
        /// </summary>
        public override int ReadMailCount()
        {
            int num = 0;
            Utilities.Retry(
                 () =>
                 {
                     string text = SendCommand("STAT");
                     if (!IsValidResponse(text))
                     {
                         return true;
                     }
                     num = ParseMailCountText(text);
                     return num == 0;
                 },
                 5);

            return num;
        }

        /// <summary>
        /// get mail header content by header text.
        /// </summary>
        /// <param name="id">mail id.</param>
        public override NameValueCollection GetMail(int id)
        {
            return InternalGetMail("TOP " + id + " 0");
        }

    }
}
